import Client from '../../assets/js/common';
import { fetch,HJappid,HJchannelcode,hgjUrl } from '../api';
import { Toast } from 'mint-ui';
const skip = () => {
  return new Promise((resolve,reject) =>{
    let myLoginTime = Client.getStore('loginTime'),
    nowTime = new Date().getTime();
    let expTime = 1000 * 60 * 60 * 24 * 30; //30Day
    if(nowTime - myLoginTime > expTime){
      Client.removeStore('login');
    };
    let storeLogin = Client.getStore("login");
    if(storeLogin && myLoginTime){
      let myFirstLoc =  Client.getSession('firstLocation');
      if(!myFirstLoc){
        changeLocation(storeLogin[1]).then(res=>{
          Client.setSession('firstLocation','yes');
        });
      }
      resolve(storeLogin);
      return;
    }
    let requestUrl = `${hgjUrl}appCustomerauth/login?appid=${HJappid}&channelcode=${HJchannelcode}&authtype=useinfo&returnUrl=${encodeURI(location.href)}`;
    let urlSrting = new Client.getQueryString();
    let param = urlSrting.params;
    //console.log("HJchannelcode",HJchannelcode);
    if(param) {
      let getParams = decodeURI(param);
      getParams = getParams.replace(/}#\//,'}');
      param = JSON.parse(getParams);
      if(param.userid && param.channelcode) {
        //console.log("param.channelcode",param.channelcode);
        (async () => {
        const userDatas = await checkUserDate(param.userid, param.channelcode);
        param.Sig = userDatas.Result.Sig;
        param.OpenId = param.userid;
        delete param.userid;
        let resolveArr = [];
        let keys = ['OpenId','Sig','channelcode'];
        for(let i=2;i>=0;i--){
          let objs = Object.assign({},param);
          resolveArr.unshift(objs);
          delete param[keys[i]];
        }
        resolveArr[2].Identifier = userDatas.Result.Identifier;
        resolveArr[2].AppId = userDatas.Result.AppId;
        Client.setStore("login",resolveArr);
        let curTime = new Date().getTime();
        Client.setStore('loginTime',JSON.stringify(curTime));
        //为对话、标点写入缓存
        let loginRes = userDatas.Result;
        let otherLogin = {
          Identifier: loginRes.Identifier,
          OpenId: loginRes.OpenId,
          Role: loginRes.Role,
          SdkAppId: loginRes.SdkAppId,
          Sig: loginRes.Sig,
          accountType: loginRes.accountType,
          UserType: null //后台接口并没有返回该字段
        }
        Client.setStore("userDatas",otherLogin);
        changeLocation(resolveArr[1]).then(resp=>{
          Client.setSession('firstLocation','yes');
        });//第一次登录时需要传一次位置信息给后端
        const sourceUrlLink = Client.getStore("sourceHref");
        location.href = sourceUrlLink;
        resolve(resolveArr);
        })()
      }else{
        Toast('回传参数缺失,请稍后再试');
      }
    } else {
      let firstUrl = location.href;
      let regs = /\?from.*?#\//g;
      firstUrl = firstUrl.replace(regs,'#/');
      //未登录状态下记录入口原地址
      Client.setStore("sourceHref",firstUrl);
      setTimeout(()=>{
        location.href = requestUrl;
      },100);
    };
  })
}
const checkUserDate = (userid, channelcode) => { // 检查用户是否有用户数据返回（签名）
  return fetch('UserInfo/userverify',{UserKey: userid,ChannelCode: channelcode});
}

const changeLocation = async (loginInfo) => {
  let pos = await getLocation();
  Client.setStore("myLocation",pos);
  await fetch('UserInfo/changelocation',{...loginInfo,Longitude:pos.currentLon,Latitude:pos.currentLat,Localhost:pos.city});
}

const getLocation = () => { // 获取当前地理位置
    return new Promise((resolve,reject)=>{
      let obj = {};
      let geolocation = new BMap.Geolocation();  
        geolocation.getCurrentPosition(r => {  
          if (geolocation.getStatus() == BMAP_STATUS_SUCCESS) {  
                obj.currentLat = r.point.lat;  
                obj.currentLon = r.point.lng;         
                let pt = new BMap.Point(obj.currentLon, obj.currentLat);  
                let geoc = new BMap.Geocoder();  
                geoc.getLocation(pt, rs => {  
                  let addComp = rs.addressComponents; 
                  obj.city = addComp.city;
                  resolve(obj);
              });
          }else{
            reject();
            Toast('获取地理定位失败');
          }
        });
    });
  }

const hgjSkip = {
  skip,
  getLocation,
  changeLocation
}
export default hgjSkip
